import React, {Component} from 'react';

import {
    View,
    Text,
    Image,
    StyleSheet,
    TouchableHighlight,
    DeviceEventEmitter
} from 'react-native';
import TabNavigator from 'react-native-tab-navigator'
import PopularPage from './popular/PopularPage'
import TrendingPage from './trending/TrendingPage'
import Toast, {DURATION} from 'react-native-easy-toast'

import {THEMECOLOR} from "../config/main";
import MyPage from "./my/MyPage";



export default class HomePage extends Component {
    constructor(props) {
        super(props)
        this.state = {
            selectedTab: 'ic_popular'
        }
    }

    componentDidMount() {
        this.listener = DeviceEventEmitter.addListener('showToast', (text) => {
            this.toast.show(text, DURATION.LENGTH_SHORT)
        })
    }

    componentWillUnmount() {
        this.listener && this.listener.remove()
    }

    _renderTab(Component, selectedTab, tabTitle, renderIcon) {
        return (
            <TabNavigator.Item
                selected={this.state.selectedTab === selectedTab}
                title={tabTitle}
                renderIcon={() => <Image style={styles.image}
                                         source={renderIcon}/>}
                renderSelectedIcon={() => <Image style={[styles.image, {tintColor: THEMECOLOR}]}
                                                 source={renderIcon}/>}
                onPress={() => this.setState({selectedTab: `${selectedTab}`})}>
                <Component {...this.props}/>
            </TabNavigator.Item>
        )
    }

    render() {
        return (
            <View style={styles.container}>
                <TabNavigator>
                    {this._renderTab(PopularPage, 'ic_popular', '最热', require('../../res/images/ic_popular.png'))}
                    {this._renderTab(TrendingPage, 'ic_trending', '推荐', require('../../res/images/ic_trending.png'))}
                    {this._renderTab(PopularPage, 'ic_favorite', '收藏', require('../../res/images/ic_favorite.png'))}
                    {this._renderTab(MyPage, 'ic_my', '我的', require('../../res/images/ic_my.png'))}
                </TabNavigator>
                <Toast ref={toast => {
                    this.toast = toast
                }}/>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    image    : {
        height: 22,
        width : 22
    }
})
